package cn.edu.sgu.www.mhxysy.converter;

import cn.edu.sgu.www.mhxysy.entity.chongwu.ChongwuAttribute;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Map<String, ?> ==> ChongwuAttribute的转换器
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class MapToChongwuAttributeConverter implements Converter<Map<String, ?>, ChongwuAttribute> {

    @Override
    public ChongwuAttribute convert(@NonNull Map<String, ?> targetMap) {
        Class<ChongwuAttribute> type = ChongwuAttribute.class;

        try {
            ChongwuAttribute instance = type.newInstance();

            for (Map.Entry<String, ?> entry : targetMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                Field field = type.getDeclaredField(key);

                field.setAccessible(true);
                field.set(instance, value);
            }

            return instance;
        } catch (InstantiationException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }

        return null;
    }

}